package work.skc.couterLonLaMapping;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : Gong.Yang
 */
@Slf4j
public class CounterExcelInfoLiner implements ReadListener<CounterExcelInfo> {

    public static void main(String[] args) {
        EasyExcel.read(Setting.data, CounterExcelInfo.class, new CounterExcelInfoLiner()).sheet().doRead();
    }

    private boolean isContinue = true;

    private List<CounterExcelInfo> data = new ArrayList<>();

    @SneakyThrows
    @Override
    public void invoke(CounterExcelInfo counterExcelInfo, AnalysisContext analysisContext) {
        data.add(counterExcelInfo);
        log.info("【运行中】size->{}", data.size());
        if (!isContinue || StrUtil.isNotBlank(counterExcelInfo.getLat())) return;
        TimeUnit.MILLISECONDS.sleep(500);
        JSONObject responseBody = search(counterExcelInfo.getName());
        Integer status = responseBody.getInt("status");
        if (status != 0) {
            isContinue = false;
            counterExcelInfo.setRemark(responseBody.getStr("message"));
            return;
        }
        JSONArray array = responseBody.getJSONArray("data");
        if (array.isEmpty()) {
            responseBody = search(counterExcelInfo.getAddress());
            status = responseBody.getInt("status");
            if (status != 0) {
                isContinue = false;
                counterExcelInfo.setRemark(status + ":" + responseBody.getStr("message"));
                return;
            }
            array = responseBody.getJSONArray("data");
            if (array.isEmpty()) return;
        }

        JSONObject location = array.getJSONObject(0).getJSONObject("location");
        counterExcelInfo.setLat(location.getStr("lat"));
        counterExcelInfo.setLng(location.getStr("lng"));
    }

    @NotNull
    private static JSONObject search(String keyword) {
        Map<String, Object> params = Map.of(
                "key", Setting.key,
                "keyword", keyword.trim(),
                "boundary", "region(全国)",
                "count", "3",
                "request_id", UUID.randomUUID().toString()
        );
        String res = HttpUtil.get(Setting.url, params);
        JSONObject responseBody = JSONUtil.parseObj(res);
        return responseBody;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        EasyExcel.write(Setting.res, CounterExcelInfo.class).sheet().doWrite(data);
    }
}
